package com.jincheng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jincheng.common.core.domain.AjaxResult;
import com.jincheng.common.core.domain.entity.SysDictData;
import com.jincheng.common.core.domain.entity.SysUser;
import com.jincheng.common.utils.DateUtils;
import com.jincheng.common.utils.DictUtils;
import com.jincheng.system.domain.Org;
import com.jincheng.system.domain.Tribe;
import com.jincheng.system.domain.UserTribe;
import com.jincheng.system.domain.dto.*;
import com.jincheng.system.mapper.ActivityMapper;
import com.jincheng.system.mapper.SysUserMapper;
import com.jincheng.system.mapper.TribeMapper;
import com.jincheng.system.mapper.UserTribeMapper;
import com.jincheng.system.service.ISysNoticeService;
import com.jincheng.system.service.ITribeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jincheng.common.utils.SecurityUtils.getUserId;

/**
 * 部落Service业务层处理
 *
 * @author DairyJay
 * @date 2025-02-27
 */
@Service
public class TribeServiceImpl implements ITribeService {
    private final TribeMapper tribeMapper;
    private final UserTribeMapper userTribeMapper;
    private final SysUserMapper userMapper;
    private final ISysNoticeService noticeService;
    private final ActivityMapper activityMapper;

    public TribeServiceImpl(TribeMapper tribeMapper,
                            UserTribeMapper userTribeMapper,
                            SysUserMapper userMapper,
                            ISysNoticeService noticeService, ActivityMapper activityMapper) {
        this.tribeMapper = tribeMapper;
        this.userTribeMapper = userTribeMapper;
        this.userMapper = userMapper;
        this.noticeService = noticeService;
        this.activityMapper = activityMapper;
    }

    /**
     * 查询部落
     *
     * @param tribeId 部落主键
     * @return 部落
     */
    @Override
    public Tribe selectTribeByTribeId(Long tribeId) {
//        return tribeMapper.selectTribeByTribeId(tribeId);
        return tribeMapper.selectById(tribeId);
    }

    @Override
    public TribeDetailDTO selectTribeDetail(Long tribeId) {
        return tribeMapper.selectTribeDetail(tribeId);
    }


    @Override
    public List<Tribe> selectList(Tribe tribe) {
        LambdaQueryWrapper<Tribe> queryWrapper = new LambdaQueryWrapper<>();
        if (tribe.getTribeId() != null && tribe.getTribeId() > 0)
            queryWrapper.eq(Tribe::getTribeId, tribe.getTribeId());

        if (tribe.getTribeName() != null && !tribe.getTribeName().isEmpty())
            queryWrapper.like(Tribe::getTribeName, tribe.getTribeName());

        if (tribe.getOrgId() != null && tribe.getOrgId() > 0)
            queryWrapper.eq(Tribe::getOrgId, tribe.getOrgId());

        if (tribe.getDeptId() != null && tribe.getDeptId() > 0)
            queryWrapper.eq(Tribe::getDeptId, tribe.getDeptId());

        if (tribe.getIntro() != null && !tribe.getIntro().isEmpty())
            queryWrapper.like(Tribe::getIntro, tribe.getIntro());

        return tribeMapper.selectList(queryWrapper);
    }

    /**
     * 查询部落列表
     *
     * @param tribe 部落
     * @return 部落
     */
    @Override
    public List<TribeDetailDTO> selectTribeList(Tribe tribe) {

        return tribeMapper.selectTribeList(tribe);
    }

    /**
     * 新增部落
     *
     * @param tribe 部落
     * @return 结果
     */
    @Override
    public int insertTribe(Tribe tribe) {
        tribe.setCreateTime(DateUtils.getNowDate());
        return tribeMapper.insertTribe(tribe);
    }

    /**
     * 修改部落
     *
     * @param tribe 部落
     * @return 结果
     */
    @Override
    public int updateTribe(Tribe tribe) {
        tribe.setUpdateTime(DateUtils.getNowDate());
        return tribeMapper.updateTribe(tribe);
    }

    /**
     * 批量删除部落
     *
     * @param tribeIds 需要删除的部落主键
     * @return 结果
     */
    @Override
    public int deleteTribeByTribeIds(Long[] tribeIds) {
        return tribeMapper.deleteTribeByTribeIds(tribeIds);
    }

    /**
     * 删除部落信息
     *
     * @param tribeId 部落主键
     * @return 结果
     */
    @Override
    public int deleteTribeByTribeId(Long tribeId) {
        return tribeMapper.deleteTribeByTribeId(tribeId);
    }

    /**
     * 查询组织列表
     *
     * @return 组织列表
     */
    @Override
    public List<Map<String, Object>> selectOrgOptions() {
        List<Org> orgList = tribeMapper.selectOrgList();
        return new ArrayList<>(orgList.stream()
                .map(org -> {
                    Map<String, Object> option = new HashMap<>();
                    option.put("label", org.getOrgName());
                    option.put("value", org.getOrgId());
                    return option;
                })
                .toList());
    }

    /**
     * 查询当前用户部落列表
     *
     * @return 部落列表
     */
    @Override
    public List<Map<String, Object>> selectTribeOptionsByUserId() {
        List<Tribe> tribeList = tribeMapper.selectTribeListByUserId(getUserId());
        return buildSelectOptions(tribeList);
    }

    /**
     * 判断用户是否在部落中
     *
     * @param userId  用户id
     * @param tribeId 部落id
     * @return 是否在部落中
     */
    @Override
    public boolean checkUserInTribe(Long userId, Long tribeId) {
        LambdaQueryWrapper<UserTribe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTribe::getUserId, userId)
                .eq(UserTribe::getTribeId, tribeId);
        return userTribeMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 查询部落列表
     *
     * @param tribeScreenDTO 筛选条件
     * @return 部落列表
     */
    @Override
    public List<Tribe> selectTribeListByScreen(TribeScreenDTO tribeScreenDTO) {
        return tribeMapper.selectActivityListByScreen(tribeScreenDTO);
    }

    /**
     * 申请加入部落
     *
     * @param tribeId 部落id
     * @param userId  用户id
     * @return 结果
     */
    @Override
    public AjaxResult apply(Long tribeId, Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        Tribe tribe = tribeMapper.selectById(tribeId);
        UserTribe userTribe = userTribeMapper.selectUserTribeByUserIdTribeId(userId, tribeId);

        if (userTribe != null) {
            if (userTribe.getStatus() == 0)
                return AjaxResult.error("已是部落成员");
            if (userTribe.getStatus() == 1)
                return AjaxResult.error("已申请过该部落，请耐心等待审核");
        }

        int temp;
        if (userTribe != null) {
            userTribe.setStatus(1);
            userTribe.setUpdateTime(DateUtils.getNowDate());
            temp = userTribeMapper.updateById(userTribe);
        } else {
            userTribe = new UserTribe();
            userTribe.setUserId(userId);
            userTribe.setTribeId(tribeId);
            userTribe.setStatus(1);
            userTribe.setCreateTime(DateUtils.getNowDate());
            userTribe.setUpdateTime(DateUtils.getNowDate());
            temp = userTribeMapper.insert(userTribe);
        }

        if (temp > 0) {
            noticeService.sendTribeApplyNotice(tribe);
            return AjaxResult.success("已成功申请该部落");
        }

        return AjaxResult.error("申请失败");
    }

    /**
     * 查询部落下拉菜单选项
     *
     * @return 部落下拉菜单选项
     */
    @Override
    public List<Map<String, Object>> selectTribeListOptions() {
        List<Tribe> tribeList = selectAll();
        return buildSelectOptions(tribeList);
    }

    /**
     * 查询用户加入的部落
     *
     * @param status 状态 {1: 已加入， 2：审核中}
     * @return 部落列表
     */
    public List<TribeSimpleDTO> selectListByUser(Integer status) {
        Long userId = getUserId();
        return tribeMapper.selectListByUser(userId, status);
    }

    /**
     * 构建下拉菜单选项
     *
     * @param tribeList 部落列表
     * @return 下拉菜单选项
     */
    private List<Map<String, Object>> buildSelectOptions(List<Tribe> tribeList) {
        return tribeList.stream()
                .map(tribe -> {
                    Map<String, Object> option = new HashMap<>();
                    option.put("label", tribe.getTribeName());
                    option.put("value", tribe.getTribeId());
                    return option;
                })
                .toList();
    }

    /**
     * 获取部落统计信息
     *
     * @return 饼图数据
     */
    @Override
    public TribeStatisticsDTO getStatistics() {
        Long total = tribeMapper.selectCount(new QueryWrapper<>());
        Double perCapita = userMapper.selectCount() * 1.0 / total;
        Double avgActivityCount = activityMapper.selectCount(new QueryWrapper<>()) * 1.0 / total;
        return new TribeStatisticsDTO(total, perCapita, avgActivityCount);
    }

    /**
     * 获取部落活动数据饼图数据
     *
     * @param type 类型
     * @return 饼图数据
     */
    @Override
    public List<PieChartDTO> getPie(String type) {
        // 校验 type 参数
        if (type == null || (!type.equals("dept") && !type.equals("org"))) {
            throw new IllegalArgumentException("Invalid type: " + type);
        }

        // 从数据库查询饼图数据
        Map<String, Map<String, Long>> pieData = tribeMapper.getPie(type);

        // 从 Redis 获取字典数据
        List<SysDictData> dictList = getDictList(type);

        // 构建并返回饼图数据
        return PieChartDTO.buildPieData(pieData, dictList);
    }

    /**
     * 根据 type 获取字典列表
     *
     * @param type 类型
     * @return 字典数据列表
     */
    private List<SysDictData> getDictList(String type) {
        String dictType = type.equals("dept") ? "sys_dept" : "tribe_org";
        return DictUtils.getDictCache(dictType);
    }
}
